package top.wshape1.rpc.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.representer.Representer;

import java.io.InputStream;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-02-02
 */

@Data
@Slf4j
public class JJRpcConfig {

    private String host = "127.0.0.1";

    private int port;

    private ConsumerConfig consumer = new ConsumerConfig();

    private ProviderConfig provider = new ProviderConfig();

    private SerializerConfig serializer = new SerializerConfig();

    private RegistryConfig registry = new RegistryConfig();

    private String token = "JJ-RPC_TOKEN";

    private CompressConfig compress = new CompressConfig();

    /*
     * 配置文件初始化
     */

    public static final JJRpcConfig CONFIG;

    static {
        JJRpcConfig CONFIG_ = null;
        final String[] CONFIG_FILE_PATH = {
                "jjrpc.yaml",
                "jjrpc.yml",
                "config/jjrpc.yaml",
                "config/jjrpc.yml",
        };
        ClassLoader loader = JJRpcConfig.class.getClassLoader();
        for (String path : CONFIG_FILE_PATH) {
            try (InputStream stream = loader.getResourceAsStream(path)) {
                if (stream == null)
                    continue;
                // yaml 文件解析
                Representer representer = new Representer(new DumperOptions());
                representer.getPropertyUtils().setSkipMissingProperties(true);
                Yaml yaml = new Yaml(representer);
                CONFIG_ = yaml.loadAs(stream, JJRpcConfig.class);
                break;
            } catch (Exception e) {
                log.error("JJRPC config file load error");
                throw new RuntimeException(e);
            }
        }

        if (CONFIG_ == null) {
            log.info("JJRPC config file not found, use default config.");
            CONFIG_ = new JJRpcConfig();
        }
        CONFIG = CONFIG_;
    }

}
